<template>
  <div>
    <canvas ref="canvas" width="800" height="600" style="border:1px solid #000000;" @click="toggleFullScreen" />
  </div>
</template>

<script>
export default {
  name: 'FullScreenCanvas',
  data() {
    return {
      video: null,
      stream: null
    }
  },
  mounted() {
    this.initVideoStream()
  },
  beforeDestroy() {
    if (this.stream) {
      this.stream.getTracks().forEach(track => track.stop())
    }
  },
  methods: {
    async initVideoStream() {
      try {
        this.stream = await navigator.mediaDevices.getUserMedia({ video: true })
        this.video = document.createElement('video')
        this.video.srcObject = this.stream
        this.video.play()
        this.video.addEventListener('play', this.drawToCanvas)
      } catch (error) {
        console.error('Error accessing the camera', error)
      }
    },
    drawToCanvas() {
      const canvas = this.$refs.canvas
      const context = canvas.getContext('2d')
      const draw = () => {
        if (this.video.paused || this.video.ended) {
          return
        }
        context.drawImage(this.video, 0, 0, canvas.width, canvas.height)
        requestAnimationFrame(draw)
      }
      requestAnimationFrame(draw)
    },
    toggleFullScreen() {
      const canvas = this.$refs.canvas
      if (!document.fullscreenElement) {
        if (canvas.requestFullscreen) {
          canvas.requestFullscreen()
        } else if (canvas.mozRequestFullScreen) { // Firefox
          canvas.mozRequestFullScreen()
        } else if (canvas.webkitRequestFullscreen) { // Chrome, Safari and Opera
          canvas.webkitRequestFullscreen()
        } else if (canvas.msRequestFullscreen) { // IE/Edge
          canvas.msRequestFullscreen()
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.mozCancelFullScreen) { // Firefox
          document.mozCancelFullScreen()
        } else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
          document.webkitExitFullscreen()
        } else if (document.msExitFullscreen) { // IE/Edge
          document.msExitFullscreen()
        }
      }
    }
  }
}
</script>

<style scoped>
canvas {
  cursor: pointer;
}
</style>
